package editor.mouse;

import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;

import editor.Context;
import editor.Mode;
import editor.layout.menu.ProjectPopUpMenu;
import editor.manager.WorkSpaceManager;
import editor.project.ProjectFile;

/**
 * Mouse Adapter
 * 
 * @author Mark Dessain 
 */
public class ProjectMouseAdapter extends MouseAdapter
{
	private JTree tree;

	/**
	 * @param tree which is selected
	 */
	public ProjectMouseAdapter(JTree tree)
	{
		super();	

		this.tree = tree;
	}

	/***
	 * 
	 * @param selPath
	 */
	private void selectFile(TreePath selPath)
	{
		if(selPath.getPathCount() > 2) 
		{        
			// Build up a directory path for the click
			DefaultMutableTreeNode selFile = (DefaultMutableTreeNode)(selPath.getLastPathComponent()); 
			ProjectFile file = ((ProjectFile)selFile.getUserObject());

			// Check it is a file
			if(file.isFile())
			{
				WorkSpaceManager.textAreaManager.add(file, false);
				
				if(Context.getMode() == Mode.TESTING)
				{
					Context.switchMode(Mode.CODING);
				}
			}
		}
	}



	/* (non-Javadoc)
	 * @see java.awt.event.MouseAdapter#mousePressed(java.awt.event.MouseEvent)
	 */
	@Override
	public void mousePressed(MouseEvent e) 
	{
		int selRow = tree.getClosestRowForLocation( e.getX(), e.getY());

		if( selRow != -1) 
		{
			Rectangle bounds = tree.getRowBounds(selRow);

			boolean x = e.getY() >= bounds.getY() && e.getY() < bounds.getY() + bounds.getHeight();
			boolean y = e.getX() > bounds.getX() && selRow < tree.getRowCount();  

			if(!(x && y)) 
			{
				selRow = -1;
			}
		}

		tree.setSelectionRow(selRow);
		TreePath selPath = tree.getPathForRow(selRow);

		// Double Left click on a valid tree node
		if(selRow != -1 && e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2)
		{
			selectFile(selPath);
		}
		// Right click in the tree area
		else if(e.getButton() == MouseEvent.BUTTON3)
			//else if (e.isPopupTrigger()) 
		{
			ProjectPopUpMenu projectPopUpMenu = new ProjectPopUpMenu(selPath);
			projectPopUpMenu.show(e.getComponent(), e.getX(), e.getY());
		}
	}
}
